package com.hopu.petshop.filter;

import com.hopu.petshop.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截未登录请求的过滤器
 */
//@WebFilter({"/*"})
public class LoginFilter implements Filter {

    //登录白名单
    public static final String[] WHITE_LIST = {"/","/login.jsp","/login.do","/code.do","login","css","js","jpg"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        //对白名单放行
        for(String white : WHITE_LIST){
            if(url.endsWith(white)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //对session中的用户进行判断
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            //强制登录
            response.sendRedirect("login.jsp");
        }else{
            //登录过放行
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
